import java.util.HashMap;
import java.util.Map;

/**
 * 974. 和可被 K 整除的子数组
 * https://leetcode.cn/problems/subarray-sums-divisible-by-k/description/
 */
class Solution2 {
    public int subarraysDivByK(int[] nums, int k) {
        int ret = 0, sum = 0;
        Map<Integer, Integer> map = new HashMap<>();
        map.put(0 % k, 1);

        for(int x : nums) {
            sum += x;
            int tmp = (sum % k + k) % k;
            if(map.containsKey(tmp)) ret += map.get(tmp);
            map.put(tmp, map.getOrDefault(tmp, 0) + 1);
        }

        return ret;
    }
}